//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useState } from "react";
import type { ReviewInfo, ReviewResultItem } from "@/api/project_review";
import { add_result, update_result } from "@/api/project_review";
import type { ProjectInfo } from "@/api/project";
import { Input, message, Modal } from "antd";
import { get_session } from "@/api/user";
import { request } from "@/utils/request";
import { useTranslation } from "react-i18next";

export interface EditReviewResultModalProps {
    resultItem?: ReviewResultItem;
    reviewInfo: ReviewInfo;
    projectInfo: ProjectInfo;
    onOk: () => void;
    onCancel: () => void;
}

const EditReviewResultModal = (props: EditReviewResultModalProps) => {
    const { t } = useTranslation();

    const [content, setContent] = useState(props.resultItem?.content ?? "");

    const addResult = async () => {
        const sessionId = await get_session();
        await request(add_result({
            session_id: sessionId,
            project_id: props.projectInfo.project_id,
            review_id: props.reviewInfo.review_id,
            content: content,
        }));
        message.info(t("text.updateSuccess"));
        props.onOk();
    };

    const updateResult = async () => {
        if (props.resultItem == undefined) {
            return;
        }
        const sessionId = await get_session();
        await request(update_result({
            session_id: sessionId,
            project_id: props.projectInfo.project_id,
            review_id: props.reviewInfo.review_id,
            result_id: props.resultItem.result_id,
            content: content,
        }));
        message.info(t("text.updateSuccess"));
        props.onOk();
    };

    return (
        <Modal open title={props.resultItem == undefined ? `${t("text.add")} ${t("project.review.result")}` : `${t("text.update")} ${t("project.review.result")}`} mask={false}
            okText={props.resultItem == undefined ? t("text.add") : t("text.update")} okButtonProps={{ disabled: content.trim() == "" }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                if (props.resultItem == undefined) {
                    addResult();
                } else {
                    updateResult();
                }
            }}>
            <Input.TextArea value={content} autoSize={{ minRows: 5, maxRows: 5 }}
                onChange={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    setContent(e.target.value);
                }} />
        </Modal>
    )
};

export default EditReviewResultModal;